package com.chinaoct.siku.gzw.report;

import com.monitorjbl.xlsx.StreamingReader;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class ExcelReader {

    public static final String OFFICE_EXCEL_XLS = "xls";
    public static final String OFFICE_EXCEL_XLSX = "xlsx";
    public static final String CSV = "csv";


    public static void main(String[] args) throws Exception{
        
        //读取xlsx
        Map<Integer, List<String[]>> map = readExcel("D:\\APP工资查询表格.xls");
        for(int n=0;n<map.size();n++){
            List<String[]> list = map.get(n);
            System.out.println("-------------------------sheet"+n+"--------------------------------");
            for(int i=0;i<list.size();i++){
                String[] arr = (String[]) list.get(i);
                for(int j=0;j<arr.length;j++){
                    if(j==arr.length-1){
                        System.out.print(arr[j]);
                    }
                    else {
                        System.out.print(arr[j]+"|");
                    }
                }
                System.out.println();
            }
        }
        //写入xlsx
      //  writeXlsx("E:/测试写入XLSX.xlsx",map);
    }
    
    public static Map<Integer, List<String[]>> readXlsx(File file){
    	   Map<Integer, List<String[]>> map = new HashMap<Integer, List<String[]>>();
           try {
//               InputStream is = new FileInputStream(file);
//               XSSFWorkbook workbook = new XSSFWorkbook(is);
               InputStream inp = new FileInputStream(file);
               Workbook workbook = StreamingReader.builder()
                       .bufferSize(16384) // 设置缓存的大小
                       .rowCacheSize(2000) // 缓存行的数量，也就是每次读取多少行到内存中，而不是一下子全都加载进内存
                       .open(inp); // 设置要打开的文件

               //Sheet sheet = workbook.getSheetAt(0);
               // 循环工作表Sheet  
               for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
                   Sheet xssfSheet = workbook.getSheetAt(numSheet);
                   if (xssfSheet == null) {
                       continue;
                   }
                   List<String[]> list = new ArrayList<String[]>();
                   
                   for (Row xssfRow : xssfSheet){
                       //Row  xssfRow = xssfSheet.getRow(row);
                       if (xssfRow == null) {
                           continue;
                       }
                       changeRow(list, xssfRow);
                   }
                   map.put(numSheet, list);
               }
           } catch (FileNotFoundException e) {
               // TODO 自动生成的 catch 块
               e.printStackTrace();
           } catch (IOException e) {
               // TODO 自动生成的 catch 块
               e.printStackTrace();
           }
    	   return map;
    }

    public static Map<Integer, List<String[]>> readXls(File file)  {
        InputStream is=null;
        POIFSFileSystem fs;
        HSSFWorkbook wb;
        HSSFSheet sheet;
        Map<Integer, List<String[]>> map = new HashMap<Integer, List<String[]>>();
        try {
            is =  new FileInputStream(file);
            fs = new POIFSFileSystem(is);
            wb = new HSSFWorkbook(fs);
            for (int numSheet = 0; numSheet < wb.getNumberOfSheets(); numSheet++) {
                sheet = wb.getSheetAt(numSheet);
                if (sheet == null) {
                    continue;
                }
                int rowNum = sheet.getLastRowNum();
                List<String[]> list = new ArrayList<String[]>();
                for(int row=0;row<=rowNum;row++){
                    HSSFRow hssfRow=sheet.getRow(row);
                    if(null==hssfRow){
                        continue;
                    }
                    changeRow(list, hssfRow);
                }
                map.put(numSheet, list);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null!=is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return map;
    }

    public static void changeRow(List<String[]> list, Row hssfRow) {
        if(hssfRow.getLastCellNum()<=0){
            return ;
        }
        String[] singleRow = new String[hssfRow.getLastCellNum()];
        for(int column=0;column<hssfRow.getLastCellNum();column++){
            Cell cell = hssfRow.getCell(column, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            switch(cell.getCellType()){
                case BLANK:
                    singleRow[column] = "";
                    break;
                case BOOLEAN:
                    singleRow[column] = Boolean.toString(cell.getBooleanCellValue());
                    break;
                case ERROR:
                    singleRow[column] = "";
                    break;
                case FORMULA:
                    //cell.setCellType(Cell.CELL_TYPE_STRING);
                    singleRow[column] = cell.getStringCellValue();
                    if (singleRow[column] != null) {
                        singleRow[column] = singleRow[column].replaceAll("#N/A", "").trim();
                    }
                    break;
                case NUMERIC:
                    if (DateUtil.isCellDateFormatted(cell)) {
                        singleRow[column] = String.valueOf(cell.getDateCellValue());
                    } else {
                        //cell.setCellType(Cell.CELL_TYPE_STRING);
                        String temp = cell.getStringCellValue();
                        // 判断是否包含小数点，如果不含小数点，则以字符串读取，如果含小数点，则转换为Double类型的字符串
                        if (temp.indexOf(".") > -1) {
                            singleRow[column] = String.valueOf(new Double(temp)).trim();
                        } else {
                            singleRow[column] = temp.trim();
                        }
                    }

                    break;
                case STRING:
                    singleRow[column] = cell.getStringCellValue().trim();
                    break;
                default:
                    singleRow[column] = "";
                    break;
            }
        }
        list.add(singleRow);
    }


    public static Map<Integer, List<String[]>> readExcel(String fileName){
        File file=new File(fileName);
        return  readExcel(file);
    }

    public static Map<Integer, List<String[]>> readExcel(File file){
        String suffiex = getSuffiex(file.getName());
        if(OFFICE_EXCEL_XLS.equals(suffiex)){
            return  readXls(file);
        }
        if(OFFICE_EXCEL_XLSX.equals(suffiex) || CSV.equals(suffiex)){
            return  readXlsx(file);
        }
        return null;
    }


    /**
     * 获取后缀
     * @param filepath filepath 文件全路径
     */
    public static String getSuffiex(String filepath) {
        if (StringUtils.isEmpty(filepath)) {
            return "";
        }
        int index = filepath.lastIndexOf(".");
        if (index == -1) {
            return "";
        }
        return filepath.substring(index + 1, filepath.length());
    }

    
    //写入Xlsx
    public static void writeXlsx(String fileName,Map<Integer,List<String[]>> map) {
        try {
            XSSFWorkbook wb = new XSSFWorkbook();
            for(int sheetnum=0;sheetnum<map.size();sheetnum++){
                XSSFSheet sheet = wb.createSheet(""+sheetnum);
                List<String[]> list = map.get(sheetnum);
                for(int i=0;i<list.size();i++){
                    XSSFRow row = sheet.createRow(i);
                    String[] str = list.get(i);
                    for(int j=0;j<str.length;j++){
                        XSSFCell cell = row.createCell(j);
                        cell.setCellValue(str[j]);
                    }
                }
            }
            FileOutputStream outputStream = new FileOutputStream(fileName);
            wb.write(outputStream);
            outputStream.close();
        } catch (FileNotFoundException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }
}
